<template>
  <view>
    <common-popup :show="show" @close="close" width="130rem">
      <template #title>
        <view>{{type=='add'?'添加':'编辑'}}会员</view>
      </template>
      <template>
        <view class="form-wrapper show-y-scroll-bar">
          <!-- <bx-form serviceName="srvretail_member_info_add" type="add"></bx-form> -->
          <view class="form-item flex-column full">
            <view class="form-label">
              <text class="text-red margin-right">*</text> 卡类型：请选择卡等级
            </view>
            <view class="check-list flex justify-start">
              <view class="check-item" v-for="item in memberLevel"
                @click="setVip(item.member_level_no,item.member_level_name)"
                :class="{active:form.member_level_no===item.member_level_no}">
                {{item.member_level_name}}
              </view>
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">
              <text class="text-red margin-right">*</text> 手机号码
            </view>
            <uni-easyinput :disabled="type!=='add'" primaryColor='#38C09E' v-model="form.member_phone"
              placeholder="请输入手机号码">
            </uni-easyinput>
          </view>
          <view class="form-item">
            <view class="form-label">
              <text class="text-red margin-right">*</text> 姓名
            </view>
            <uni-easyinput :disabled="type==='detail'" primaryColor='#38C09E' v-model="form.member_name"
              placeholder="请输入姓名"></uni-easyinput>
          </view>

          <view class="form-item">
            <view class="form-label">
              <text class="text-white margin-right">*</text> 生日
            </view>
            <view class="form-content">
              <uni-datetime-picker :end="birthdayEnd" :disabled="type==='detail'" primaryColor='#38C09E' type="date"
                :value="form.birthday" @change="bindDateChange" />
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">
              <text class="text-white margin-right">*</text>性别
            </view>
            <view class="form-radio form-content">
              <radio-group @change="sexChange" :disabled="type==='detail'">
                <label class="margin-right" v-for="(item, index) in sexList" :key="item">
                  <radio :value="item" :checked="item === form.sex" color="#38C09E" />
                  <text class="label margin-left margin-right">{{item}}</text>
                </label>
              </radio-group>
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">
              <text class="text-white margin-right">*</text>有效期
            </view>
            <view class="form-content">
              <uni-datetime-picker :disabled="type==='detail'" primaryColor='#38C09E' type="date"
                :value="form.member_expiration_time" @change="bindLimitDateChange" />
            </view>

          </view>
          <view class="form-item">
            <view class="form-label">
              <text class="text-white margin-right">*</text>状态
            </view>
            <view class="form-radio form-content">
              <radio-group @change="stateChange" :disabled="type==='detail'">
                <label class="margin-right" v-for="(item, index) in stateList" :key="item">
                  <radio :value="item" :checked="item === form.member_state" color="#38C09E" />
                  <text class="label margin-left margin-right">{{item}}</text>
                </label>
              </radio-group>
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">
              <text class="text-red margin-right">*</text>
              登录密码
            </view>
            <uni-easyinput :disabled="type==='detail'" primaryColor='#38C09E' type="password" v-model="form.pass_word"
              placeholder="请输入内容">
            </uni-easyinput>
            <!-- <input v-model="form.pass_word" password class="form-input" type="text" placeholder="请输入密码" /> -->
          </view>
          <view class="form-item">
            <view class="form-label">
              <text class="text-red margin-right">*</text>
              确认密码
            </view>
            <uni-easyinput :disabled="type==='detail'" primaryColor='#38C09E' type="password"
              v-model="form.confirm_pass_word" placeholder="请输入内容">
            </uni-easyinput>
            <!-- <input v-model="form.confirm_pass_word" password class="form-input" type="text" placeholder="请再次输入密码" /> -->
          </view>
          <view class="form-item label-top">
            <view class="form-label ">
              <text class="text-white margin-right">*</text>地址
            </view>
            <uni-easyinput :autoHeight="true" :disabled="type==='detail'" primaryColor='#38C09E' type="textarea"
              v-model="form.address" placeholder="请输入备注"></uni-easyinput>
            <!-- <textarea class="form-textarea" placeholder="请输入备注" v-model="form.remarks"></textarea> -->
          </view>
          <view class="form-item label-top">
            <view class="form-label ">
              <text class="text-white margin-right">*</text>备注
            </view>
            <uni-easyinput :autoHeight="true" :disabled="type==='detail'" primaryColor='#38C09E' type="textarea"
              v-model="form.remarks" placeholder="请输入备注"></uni-easyinput>
            <!-- <textarea class="form-textarea" placeholder="请输入备注" v-model="form.remarks"></textarea> -->
          </view>
          <view class="form-item ">
            <view class="form-label">
              <text class="text-white margin-right">*</text>账号保护
            </view>
            <view class=" flex justify-start">
              <view class="check-item margin-right" v-for="item in guardList" @click="setGuard(item)"
                :class="{active:form.account_protect===item}">
                {{item}}
              </view>
            </view>
          </view>

          <!-- <u-alert :title="alertText" type="warning" :closable="true" v-if="alertText"></u-alert> -->

        </view>
        <view class="form-button flex justify-end" v-if="type==='add'">
          <button class="button lg normalsize line-white margin-right-lg" @click="confirm()">确认开卡</button>
          <button class="button lg normalsize" @click="openRecharge">开卡并充值</button>
        </view>
        <view class="form-button flex justify-end" v-if="type==='update'">
          <button class="button lg normalsize line-white margin-right-lg" @click="cancel">取消</button>
          <button class="button lg normalsize" @click="confirmUpdate">确认修改</button>
        </view>
      </template>
    </common-popup>
    <!-- <vip-recharge :show="showRecharge"></vip-recharge> -->
  </view>
</template>

<script>
  /**
   * @description 新增/编辑会员弹窗
   * @property {Boolean} show - 是否显示新增会员弹窗
   * @property {String} type=[add|update|detail] 类型，新增、编辑、详情
   * @property {String} memberNo - 当前选择会员的会员编号 type为detail或update时需要传入
   * @event {Function()} close - 弹窗关闭事件，点击右上角关闭图标时触发
   * @event {Function()} success - 新增/编辑成功事件 返回新增/编辑后的会员信息
   * @event {Function()} fail - 新增/编辑失败事件 返回失败提示信息
   * @example   <add-member :show="show" type="update" :memberNo="memberNo" @close="close" @success="" @fail="" ></add-member>
   */

  export default {
    name: "add-member",
    props: {
      show: {
        type: Boolean
      },
      // 会员编号
      memberNo: {
        type: String
      },
      type: {
        type: String,
        default: 'add', //add update detail
      },
      showRecharge: Boolean
    },
    computed: {
      memberInfo() {
        return this.memberList.find(item => this.memberNo && item.menber_no === this.memberNo)
      }
    },
    data() {
      const birthdayEnd = this.dayjs().format("YYYY-MM-DD")
      return {
        birthdayEnd: birthdayEnd,
        // memberInfo: null,
        alertText: "",
        styles: {
          color: '#333',
          borderColor: '#e5e5e5'
        },
        // showRecharge: false, //会员充值弹窗
        form: {
          member_name: '',
          "member_phone": "",
          "pass_word": "gmcc1234@",
          "confirm_pass_word": "gmcc1234@",
          "sex": "",
          "birthday": "",
          "member_level_no": "",
          "member_level": "",
          // "be_overdue_state": "",
          "account_protect": "免密",
          "remarks": "",
          address: "", //地址
          member_expiration_time: "", //有效期
          member_state: "生效", //会员状态
        },
        curVip: "普通会员",
        memberLevel: [], // 会员等级列表
        curGuard: "免密",
        guardList: [
          '免密', '验证码验证'
        ],
        curSex: "男",
        sexList: [
          '男', '女'
        ],
        stateList: ['生效', '禁用', '挂失']
      };
    },
    created() {
      this.getMemberLevel()
    },
    watch: {
      memberNo: {
        immediate: true,
        handler(newValue, oldValue) {
          if (newValue && ['detail', 'update'].includes(this.type)) {
            let memberInfo = this.memberList.find(item => item.menber_no === newValue)
            if (memberInfo?.id) {
              Object.keys(this.form).forEach(key => {
                this.form[key] = memberInfo[key]
              })
            } else {
              this.close()
            }
          }
        }
      }
    },
    methods: {
      onValid() {
        if (!this.form.member_name) {
          this.alertText = '请输入会员姓名'
          uni.showToast({
            title: '请输入会员姓名',
            icon: "none"
          })
          return
        } else if (!this.form.member_phone) {
          this.alertText = '请输入会员手机号'
          uni.showToast({
            title: '请输入会员手机号',
            icon: "none"
          })
          return
        } else if (!this.form.member_level_no) {
          this.alertText = '请选择卡等级'
          uni.showToast({
            title: '请选择卡等级',
            icon: "none"
          })
          return
        } else if (!this.form.pass_word) {
          this.alertText = '请输入登录密码'
          uni.showToast({
            title: '请输入登录密码',
            icon: "none"
          })
          return
        } else if (this.form.pass_word.length < 8 || this.form.pass_word.length > 16) {
          this.alertText = '登录密码限制8-16位字符'
          uni.showToast({
            title: '登录密码限制8-16位字符',
            icon: "none"
          })
          return
        } else if (this.form.pass_word !== this.form.confirm_pass_word) {
          this.alertText = '两次输入的密码不一致'
          uni.showToast({
            title: '两次输入的密码不一致',
            icon: "none"
          })
          return
        }
        return true
      },
      async confirmUpdate() {
        const isValid = this.onValid()
        if (isValid === true) {
          return await this.updateMember()
        }
      },
      async confirm(toRecharge = false) {
        const isValid = this.onValid()
        if (isValid === true) {
          return await this.createMember(toRecharge)
        }
      },
      async getMemberLevel() {
        const url = `/retail/select/srvretail_member_level_select`
        const req = {
          "serviceName": "srvretail_member_level_select",
          "queryMethod": "select",
          "distinct": false,
          "colNames": ["*"],
          "condition": [{
            "colName": "level_state",
            "ruleType": "eq",
            "value": "可用"
          }],
          "page": {
            "pageNo": 1,
            "rownumber": 20
          }
        }
        const res = await this.$http.post(url, req)
        if (res?.data?.state === 'SUCCESS') {
          this.memberLevel = res.data.data
          if (res.data.data.length > 0) {
            this.curVip = res.data.data[0].member_level_no
          }
        }
      },
      bindLimitDateChange(e) {
        if (this.type === 'detail') {
          return
        }
        this.form.member_expiration_time = e
      },
      bindDateChange(e) {
        if (this.type === 'detail') {
          return
        }
        this.form.birthday = e
      },
      // 更新会员信息
      async updateMember() {
        const service = 'srvretail_member_info_custom_update'
        // const service = 'srvretail_member_info_update'
        const url = `/retail/operate/${service}`
        let data = {}
        Object.keys(this.form).forEach(key => {
          if (this.memberInfo[key] !== this.form[key]) {
            data[key] = this.form[key]
          }
        })
        const req = [{
          "serviceName": service,
          "condition": [{
            "colName": "id",
            "ruleType": "eq",
            "value": this.memberInfo.id
          }],
          "data": [data]
        }]
        const res = await this.$http.post(url, req)
        if (res?.data?.state === 'SUCCESS') {
          const info = res?.data?.response[0]?.response?.effect_data[0]
          this.$emit('success', {
            tyep: this.type,
            service: service,
            success: true,
            data: info
          })
          // queryMembers()
          return info
        } else {
          this.$emit('fail', {
            tyep: this.type,
            service: service,
            success: false,
            msg: res?.data?.resultMessage
          })
          uni.showToast({
            title: res?.data?.resultMessage,
            icon: 'none'
          })
          return res?.data?.resultMessage
        }
      },
      // 创建会员
      async createMember(toRecharge = false) {
        const url = `/retail/operate/srvretail_member_custom_info_add`
        const data = {}
        Object.keys(this.form).forEach(key => {
          if (this.form[key]) {
            data[key] = this.form[key]
          }
        })
        const req = [{
          "serviceName": "srvretail_member_custom_info_add",
          "condition": [],
          "data": [{
            "store_no": this.tenantInfo?.tenant_no,
            "store_name": this.tenantInfo?.tenant_name,
            "be_overdue_state": "未过期",
            "recharge_amount": 0,
            "give_amount": 0,
            "balance": 0,
            "cumul_get_points": 0,
            "cumul_consumption_points": 0,
            "integral": 0,
            "consumption_amount": 0,
            "usable_recharge_amount": 0,
            "usable_gift_amount": 0,
            "member_state": "生效",
            ...data,
            // "member_expiration_time": "2022-11-22",
          }]
        }]
        const res = await this.$http.post(url, req)
        uni.showToast({
          title: res.data.resultMessage,
          icon: 'none'
        })
        if (res?.data?.state === 'SUCCESS') {
          // 创建成功
          const curMemberInfo = res?.data?.response[0]?.response?.effect_data[0]
          // this.$store.commit('SET_STATE', {
          //   key: '$curMember',
          //   value: curMemberInfo
          // })
          this.$emit('success', curMemberInfo, toRecharge)
          return {
            success: true,
            data: curMemberInfo
          }
        } else {
          // 创建失败
          this.$emit('fail', res?.data?.resultMessage)
          uni.showToast({
            title: res?.data?.resultMessage,
            icon: 'none'
          })
          return {
            success: false,
            msg: res?.data?.resultMessage
          }
        }
      },
      cancel() {
        this.$emit('close', {
          type: 'cancel'
        })
      },
      close() {
        this.$emit('close')
      },
      stateChange(e) {
        if (this.type === 'detail') {
          return
        }
        this.form.member_state = e.detail.value
      },
      sexChange(e) {
        if (this.type === 'detail') {
          return
        }
        this.form.sex = e.detail.value
      },
      setVip(e, name) {
        if (this.type === 'detail') {
          return
        }
        this.form.member_level_no = e
        this.form.member_level = name
      },
      setGuard(e) {
        if (this.type === 'detail') {
          return
        }
        this.form.account_protect = e
      },
      openRecharge() {
        this.confirm(true).then(res => {
          if (res?.success === true) {
            // 创建会员成功，关闭新增会员弹窗并弹出会员充值弹窗
            // this.$emit('update:showRecharge', false)
            this.$emit('close', res.data, true)
          } else if (res.msg) {
            uni.showToast({
              title: res.msg,
              icon: "none"
            })
            this.$emit('fail', res.msg)
          }
        })
        // this.showRecharge = true
      }
    },
  }
</script>

<style lang="scss" scoped>
  .popup-content {
    height: auto;
  }

  .form-wrapper {
    // display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    padding: 2rem 0;
    padding-bottom: 10rem;
    min-width: 120rem;
    max-height: 85vh;

    // overflow-y: auto;
    .full {
      min-width: 100%;
    }

    ::v-deep .label {
      font-size: 2.4rem;
    }



  }

  .form-button {
    display: flex;
    min-width: 120rem;
    justify-content: flex-end;
    position: absolute;
    right: 10rem;
    bottom: 12rem;
    height: 0;
    padding: 0;
  }

  .form-item {
    display: inline-flex;
    flex-direction: row;
    align-items: center;
    // justify-content: space-between;
    margin-top: 1.5rem;
    // min-width: 45%;
    flex: 1;
    padding-right: 2rem;
    // margin-right: 4rem;
    width: 50%;
    padding-right: 2rem;

    &:nth-child(2n+1) {
      margin-right: 0;
      padding-right: 0;
    }

    &.flex-column {
      flex-direction: column;
      align-items: flex-start;

      .form-label {
        padding-top: 0;
      }
    }

    &.label-top {
      align-items: flex-start;

      .form-label {
        // padding-top: 0;
      }
    }

    .form-label {
      font-size: $retail-font-size-sm;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      text-align: left;
      padding: 1.5rem 0;
      margin-right: 1rem;
      min-width: 12rem;
    }

    ::v-deep .uni-easyinput__content-textarea {
      // min-height: 10vh;
    }

    .form-input {
      border: 1px solid #e5e5e5;
      border-radius: 1rem;
      height: 6rem;
      padding: 1.5rem;
      width: 32rem;

      &.place-holder {
        color: grey;
      }
    }

    .form-content {
      flex: 1;
    }

    .form-radio {
      // min-width: 32rem;
      display: flex;
      align-items: center;

      ::v-deep radio {}
    }

    .form-textarea {
      width: 32rem;
      height: 10rem;
      background-color: #f5f5f5;
      padding: 1.5rem;
      border-radius: 1rem;
    }
  }


  .check-list {
    display: flex;
    justify-content: flex-start;
    width: 100%;
    flex-wrap: wrap;
  }

  .check-item {
    padding: 0 2rem;
    min-width: 13.5rem;
    height: 6rem;
    line-height: 6rem;
    text-align: center;
    border-radius: 1rem;
    border: 1px solid #e5e5e5;
    color: #333;
    font-size: $retail-font-size-sm;
    margin-right: 2rem;
    margin-bottom: 1rem;

    &.active {
      border-color: $retail-color-primary;
      color: $retail-color-primary;
      background-color: $retail-color-primary-light;
    }
  }

  .disable {
    pointer-events: none;
    filter: grayscale(100%);
  }
</style>
